package com.robot.agent.controller;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.robot.agent.client.MemberClient;
import com.robot.agent.pojo.Agent;
import com.robot.agent.pojo.AgentMember;
import com.robot.agent.pojo.client.Member;
import com.robot.agent.service.AgentService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.robot.agent.service.AgentMemberService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;

import javax.servlet.http.HttpServletRequest;

/**
 * 代理商名下会员
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/agentMember")
public class AgentMemberController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AgentMemberService agentMemberService;
    @Autowired
    private AgentService agentService;

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * agent表status状态 0-禁用 1-启用
     */
    private String agentStatusEnable = "1";

    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(StatusCode.SUCCESS_QUERY, agentMemberService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(StatusCode.SUCCESS_QUERY, agentMemberService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<AgentMember> pageList = agentMemberService.findSearch(searchMap, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<AgentMember>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.SUCCESS_QUERY, agentMemberService.findSearch(searchMap));
    }

    /**
     * 通过area查找代理商名下的今日会员
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "findTodayMembers/{page}/{size}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Result findAgentMembersByAreaOrderByRegisteredAtDescToday(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        Agent agentInDb = agentService.findById(claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        Page<AgentMember> pageData = agentMemberService.findAgentMembersByAreaOrderByRegisteredAtDescToday(agentInDb.getArea(), page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 通过area查找代理商名下的最近7日会员
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "findWeekMembers/{page}/{size}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Result findAgentMembersByAreaOrderByRegisteredAtDescWeek(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        Agent agentInDb = agentService.findById(claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        Page<AgentMember> pageData = agentMemberService.findAgentMembersByAreaOrderByRegisteredAtDescWeek(agentInDb.getArea(), page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 通过area查找代理商名下的总会员
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "findTotalMembers/{page}/{size}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Result findAgentMembersByAreaOrderByRegisteredAtDescTotal(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        Agent agentInDb = agentService.findById(claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        Page<AgentMember> pageData = agentMemberService.findAgentMembersByAreaOrderByRegisteredAtDescTotal(agentInDb.getArea(), page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * agent端新增会员提醒
     *
     * @return
     */
    @RequestMapping(value = "newMemberReminder", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Result newMemberReminder() {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断


        String agentMemberKey = "agentMember_";
        List list = (List) redisTemplate.opsForList().rightPop(agentMemberKey + claims.getId());
        if (list == null) {
            logger.info("agentModule's newMemberReminder list is null");
            return new Result(StatusCode.SUCCESS_QUERY);
        }
        logger.info("agentModule's newMemberReminder list is not null and list=" + list);
        Member memberInDb = JSON.parseObject(memberClient.thirdFindMemberById(list.get(0).toString()), Member.class);
        if (memberInDb == null) {
            logger.info("agentModule's newMemberReminder memberInDb is null");
            return new Result(StatusCode.SUCCESS_QUERY);
        }
        return new Result(StatusCode.SUCCESS_QUERY, memberInDb);
    }
}
